var product={
    inventory:0,
    totalInventoryCount:0,
    sku:[],
    ktotal:0,
    total:0,
    buyProperty:"",
    init:function(){
        var maxHeight=$.util.page.getHeight();
        $("#opacity").css("height",maxHeight);
        this.pros=window.pros;
        this.getCartGoodsNum();
        this.initEvent();
    },
    initEvent:function(){
        $("#cartInfo").click(function(){
            var p=$.util.getParamAsObject();
            var customerId=$.util.getParam("customerId");
            var params=$.extend(p,{
                "sid":"-1",
                "type":"buy"
            });
            params=encodeURIComponent(JSON.stringify(params));
            location.href = 'call.html?customerId='+customerId+'&module=product&method=getCart&params=' + params;
        })
    },
    getCartGoodsNum:function() {
        var customerId=$.util.getParam("customerId");
        $.req.get("call.json?module=product&customerId="+customerId+"&method=getCarNum",{
            params:{
                "type":"buy",
                "sid":"-1"
            }
        },function(data){
            if(!data.code && data.total > 0){
                if(data && data.total > 0){
                    $("#cartInfo").show();
                    $("#cartInfo .proNum").text(data.total || 0);
                    $("#cartInfo .proPrice:eq(0)").find("span").text(data.price || 0);
                    $("#cartInfo .proPrice:eq(1)").find("span").text(data.chPrice || 0);
                }else{
                    $("#cartInfo").hide();
                }
            } else{
                $("#cartInfo").hide();
            }
        });
    },
    toDetail:function(id){
        window.event.cancelBubble = true;
        var customerId=$.util.getParam("customerId");
        var p=$.util.getParamAsObject();
        if(p&& p.qId){
            var params={
                "id":id,
                "miUId": p.miUId,
                "qId": p.qId,
                "fromGuid":p.fromGuid
            }
        }else{
            var params={
                "id":id
            }
        }
        params=encodeURIComponent(JSON.stringify(params));
        location.href= window.baseUrl+'call.html?customerId='+customerId+'&module=product&method=getProduct&params='+params;
    },
    move:function(){
        $('html').removeClass('noscroll');
    },
    stop:function(){
        $('html').addClass('noscroll');
    },
    productShow:function(){
        var scroll = $(window).scrollTop();
        $("#productInfo").css("bottom",-(scroll+$("#productInfo").height()+50)+"px");
        $("html").css("margin-top","-"+scroll+"px");
        this.stop();
        $(".mark").show();
        $("#productInfo").addClass("show").css("bottom",-scroll);
    },
    _initClickEvent: function() {
        var me = this;
        if ((me.inventory == 0 || me.totalInventoryCount > 0 || me.sku.length>0)) {
            $(".sub,.plus").on("click", function (e) {
                me._initBuyNum(e);
            });
            $(".mod_property dd").on("click", function (e) {
                me.statisticSelected(this);
            });
            $("#buy-now").click(function () {
                if (!$(this).hasClass("btn_disabled")) {
                    me._initBuy();
                }
            });
        }
        $("#prompt a").click(function () {
            if($("#prompt input[type='checkbox']").is(":checked")){
                $.util.cookie("prompt",1,{"expires":365,"path":"/"});
            }
            $("#prompt").hide();
        })
        $("#free-list dd").click(function(){
            $(this).addClass("current").siblings().removeClass("current");
            $("#invitation").show();
            me.countPerNum();
        })
        $("#close").click(function(){
            var scroll = $("html").css("margin-top");
            $("#productInfo").css("bottom",($("#productInfo").height()+50-parseInt(scroll))*-1);
            $("#productInfo").one("webkitTransitionEnd",function(){
                $("#productInfo").removeClass("show");
                me.move();
                $("#opacity").hide();$(".mask").hide();
                $("html").css("margin-top",null);
                $(window).scrollTop(-parseInt(scroll));
            })
        });
    },
    getCustomizedInfo:function(){
        var customizedInfo = [];
        $("#customized li").each(function(){
            var name = $(this).find('.customizedName').html(),
                descrip =  $(this).find('.customizedDescription'),
                description = descrip.val(),
                type = descrip.data('type');
            var other = {};
            if(descrip.data("type")==1){
                description = description.replace("T"," ");
            }else if(descrip.data("type")==6){
                var province=$(this).find('.province input').val()||'',
                    city=$(this).find('.city input').val()||'',
                    country=$(this).find('.area input').val()||'';
                if((!$(this).find('.province').is(":hidden")&&!province)||(!$(this).find('.city').is(":hidden")&&!city)||(!$(this).find('.area').is(":hidden")&&!country)){
                    description = '';
                }else{
                    description = province+city+country;
                    other = {
                        province:province,
                        city:city,
                        country:country
                    }
                }
                if(!description){
                    $.util.alert(name+"填写错误");
                    $(this).find('.customizedClass').addClass('error');
                    customizedInfo = false;
                    return false;
                }else{
                    $(this).find('.customizedClass').removeClass('error');
                }
            }else if(descrip.data("type")==4){
                if(!(/^1\d{6,10}$/.test(description))){
                    description = '';
                }
            }else if(descrip.data("type")==5){
                if(!(/^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(description))){
                    description = '';
                }
            }
            if(!description){
                $.util.alert(name+"填写错误");
                $(this).find('.customizedDescription').addClass('error');
                customizedInfo = false;
                return false;
            }else{
                $(this).find('.customizedDescription').removeClass('error');
            }
            customizedInfo.push({
                name:name,
                type:type,
                description:description,
                other:other
            })
        })
        return customizedInfo;
    },
    buy:function(ctrl){
        var me = this;
        var p=$.util.getParamAsObject();
        var data=me.curData;
        if (!$(ctrl).hasClass("btn-disabled")) {
            if ($("#prop-list dl").length != 0) {
                var size = $("#prop-list dd.current").size();
                var sku = me.sku;
                var isValidate = true;
                var sizes = '';
                var colors = '';
                $("#prop-list dl").each(function () {
                    if (!$(this).find("dd").hasClass("current")) {
                        $.util.alert('请选择' + $(this).find("dt").text());
                        isValidate = false;
                        return false;
                    } else {
                        sizes = $("#prop-list dl:eq(0)").find("dd.current").data("name");
                        colors = $("#prop-list dl:eq(1)").find("dd.current").data("name");
                    }
                });
                if (!isValidate) {
                    return false;
                }
            }
            if ($("#free-list").length && !$("#free-list dd").hasClass("current")) {
                $.util.alert('请选择价格');
                return;
            }
            var customerId = $.util.getParam("customerId");
            if ($("#stock-num") && $("#stock-num").html() == 0) {
                $.util.alert("库存不足");
                return;
            }
            var params = {
                "pids":$(ctrl).data("id"),
                "sizes": sizes,
                "colors": colors,
                "counts": $("#buyNum").val(),
                "type":"buy"
            };
            if(window.buyParams) {
                params = $.extend(params, window.buyParams);
            }
            var customizedInfo = this.getCustomizedInfo();
            if(!customizedInfo){return;}
            $(ctrl).addClass("btn-disabled");
            $.util.pageLoading.show();
            params.teamId = window.teamId; //团购下订单的时候记录订单属于哪个团
            params.teamBuyType = "team";
            params.customizedInfo=JSON.stringify(customizedInfo);
            $.req.get("call.json?customerId=" + customerId + "&module=product&method=preSubmitOrder", {
                params: params
            }, function (data) {
                if (data.hasOwnProperty('code')) {
                    $(this).removeClass("btn_disabled");
                    $.util.showMsg(data.msg);
                    $.util.pageLoading.hide();
                } else {
                    var p = {
                        "tplid": 1,
                        "id": data.id
                    }
                    viewPage.tuan.createTeamOrder(data.id, function (data) {
                        if (data && !data.code) {
                            $.util.pageLoading.hide();
                            $(this).removeClass("btn_disabled");
                            location.href = window.hrefPath + '&module=product&method=getOrderDetail&force=1&params=' + encodeURIComponent(JSON.stringify(p));
                        }
                    });
                }
            });
        }
    },
    _initBuy: function() {
        var me=this;
        var p=$.util.getParamAsObject();
        var data=me.curData;
        if (!$("#buy-now").hasClass("btn-disabled")) {
            if ($("#prop-list dl").length != 0) {
                var size = $("#prop-list dd.current").size();
                var sku = me.sku;
                var isValidate=true;
                var sizes = '';
                var colors = '';
                $("#prop-list dl").each(function(){
                    if(!$(this).find("dd").hasClass("current")){
                        $.util.alert('请选择'+$(this).find("dt").text());
                        isValidate=false;
                        return false;
                    }else{
                        sizes=$("#prop-list dl:eq(0)").find("dd.current").data("name");
                        colors = $("#prop-list dl:eq(1)").find("dd.current").data("name");
                    }
                });
                if(!isValidate){
                    return false;
                }
            }
            if($("#free-list").length&&!$("#free-list dd").hasClass("current")){
                $.util.alert('请选择价格');
                return;
            }

            var customerId = $.util.getParam("customerId");
            if ($("#stock-num") && $("#stock-num").html() == 0) {
                $.util.alert("库存不足");
                return;
            }
            var pa={
                "pid":$("#buy-now").data("id"),
                "type":"buy",
                "count":$("#buyNum").val(),
                "size":sizes,
                "color":colors,
                "qId":p.qId,
                "miUId":p.miUId,
                "vId":p.vId,
                "shareId":p.sId,
                "shareFormGuid":p.fromGuid || ""
            };
            if($("#free-list").length){
                pa.deposit=$("#free-list dd.current").data("value");
            }
            $.util.pageLoading.show();
            $(this).addClass("btn-disabled");
            var customerId=$.util.getParam("customerId");
            $.req.get("call.json?module=product&customerId="+customerId+"&method=updateOrderDetail", {
                params: pa
            },function(data){
                if(!data.code){
                    $.util.pageLoading.hide();
                    $.util.alert("加入购物车成功");
                    me.getCartGoodsNum();
                    $("#close").close();
                }
            })
        }
    },
    statisticSelected: function(e) {
        var me=this;
        var b = $(e);
        if (!b.hasClass("current") && !b.hasClass("disabled")) {
            b.addClass("current").siblings().removeClass("current");
            var c = b.parent();
            var selectedCount=$(".mod_property dd.current").size();
            if(selectedCount==me.sku.length){
                var key=[];
                $(".mod_property dd.current").each(function(){
                    key.push($(this).data("name"));
                });
                if(key.length>0){
                    key=key.join("|");
                }
                me.buyProperty=key;
                var stock = me.availSku[key];
                if (stock) {
                    $("#buyNum").val(1);
                    var stockCount = stock.inventoryCount;
                    $("#stock-num").html(stockCount);
                    $("#buyNum").data("nowKc",stockCount);
                    if(stockCount<2) {
                        $("#plus").addClass("disabled");
                    } else {
                        $("#plus").removeClass("disabled");
                    }
                    if(stockCount>0){
                        $("#inventory_count").show();
                        $(".soldOut").hide();
                    }else {
                        $("#inventory_count").hide();
                        $(".soldOut").show();
                    }
                }

                if (me.inventory == 1 && stockCount == 0) {
                    $("#buy-now").addClass("btn_disabled");
                    $("#buy-now").removeClass("btn_strong");

                }
                if (me.inventory == 1 && stockCount > 0) {
                    $("#buy-now").removeClass("btn_disabled");
                    $("#buy-now").addClass("btn_strong")
                }
            }
        }
    },
    _initBuyNum: function(e) {
        var me=this;
        var buyNum = $("#buyNum"),
            target = $(e.target),
            type = target.attr("tag"),
            num = 1 * buyNum.val();
        if (target.hasClass("disabled")) {
            return;
        }
        if (num) {
            if (isNaN(num)) {
                buyNum.val(1);
            } else {
                var total = me.total;
                var ktotal = me.ktotal || 999;
                if ($("#prop-list dl").length != 0) {
                    var size = $("#prop-list dd.current").size();
                    var color = $("#prop-list dl").eq(1).find("dd.current").data("value");
                    var sku = me.sku;
                    var isValidate=true;
                    $("#prop-list dl").each(function(){
                        if(!$(this).find("dd").hasClass("current")){
                            $.util.alert('请选择'+$(this).find("dt").text());
                            isValidate=false;
                            return false;
                        }
                    });
                    if(!isValidate){
                        return false;
                    }
                    ktotal = buyNum.data('nowKc') || 999;
                }
                if($("#free-list").length&&!$("#free-list dd").hasClass("current")){
                    $.util.alert('请选择价格');
                    return;
                }
                if (type == "add") {
                    if (ktotal && num < parseInt(ktotal)) {
                        buyNum.val(++num);
                        $("#sub").removeClass("disabled");
                        if(num>=ktotal){
                            $("#plus").addClass("disabled");
                        }
                    }
                } else {
                    if (num > 1) {
                        buyNum.val(--num);
                        $("#plus").removeClass("disabled");
                        if (num < 2) {
                            $("#sub").addClass("disabled");
                        }
                    }
                }
            }
        }
        me.countPerNum();
    },
    countPerNum:function(){
        var pNum = Math.ceil($.util.accSub($("#free-list dd.current").data("price"),$("#free-list dd.current").data("value")));
        var num = $("#buyNum").val();
        pNum = num*pNum;
        if(pNum){
            $("#invitation").html("需要"+pNum+"个好友帮忙减价");
        }else{
            $("#invitation").html( "正常价格，可直接购买。");
        }
    },
    loadProInfo:function(id,freebuy){
        var me=this;
        $(".mask").show();
        me.stopPropagation();
        if(parseInt(freebuy)){
            if(!parseInt($.util.cookie("prompt"))){
                $("#prompt").show();
            }
            $("#invitation").hide();
        }
        if(me.pros){
            var data=null;
            $.each(me.pros,function(){
                if(this.id==id){
                    data = this;
                    return false;
                }
            })
            if(data){
                me.inventory = parseInt(data.inventory || 0);
                me.totalInventoryCount = parseInt(data.inventoryCount || 0);
                me.total=parseInt(data.surplusNum || 0);
                data.inventory=parseInt(data.inventory);
                data.inventoryCount=parseInt(data.inventoryCount);
                if(data.availSku){
                    me.availSku=JSON.parse(data.availSku) || "";
                }
                me.ktotal=parseInt(data.inventoryCount || 0);
                me.color=data.color;
                me.size=data.size;
                me.curData=data;
                var sku=[];
                if (data.size) {
                    sku.push({"pList": data.size, "pName":data.sizeUnit,"availSku":data.availSku});
                }
                if (data.color != null) {
                    sku.push({"pList": data.color, "pName":data.colorUnit,"availSku":data.availSku});
                }
                me.sku=sku;
                if(data.picUrl1&&typeof(data.picUrl1)=='string'){
                    data.picUrl1 = JSON.parse(data.picUrl1);
                }
                me.renderPro(data);
                me._initClickEvent();
            }
        }
    },
    renderPro:function(data){
        var me=this;

        if(data){
            if(data.color){
                data.colorObj=JSON.parse(data.color);
                data.colorUrl = JSON.parse(data.colorurl);
            }
            if(data.size){
                data.sizeObj=JSON.parse(data.size);
                data.sizeUrl = JSON.parse(data.sizeurl);
            }
            data.freeBuy = parseInt(data.freeBuy);
            var html=template("productInfoTpl", data),
                container=$("#productInfo");
            container.html(html);
            $('#m_cityed').citys({required:false});
            $("#productInfo").width($(window).width());
            this.productShow();
        }
    },
     stopPropagation:function(e) {
        e = e || window.event;
        if(e.stopPropagation) { //W3C阻止冒泡方法
            e.stopPropagation();
        } else {
            e.cancelBubble = true; //IE阻止冒泡方法
        }
    }
}

